#coding=utf-8
import thread,time,httplib2
import models, excep,suggest

url = "http://hq.sinajs.cn/list=%s"
def get_market(code):
    return suggest.query(code)[0].market

def get_p_by_row(row):
    
    import datetime as dt
    now = dt.datetime.now().isoformat()
    
    s = row
    
    i = s.find('=')
    code = s[i-6: i]
    rp = models.RTPrice(code)
    
    try:
        start = s.find('"') + 1    
        s = s[start:]
        end = s.find('"')  
        s = s[:end]
        
        data = s.split(',')[1:]
       
        rp.open = float( data[0] )
        rp.now = float( data[2] )
        
        pre_close = float(data[1])
        rp.change = (rp.now - pre_close)/pre_close *100
        rp.jump = (rp.open - pre_close)/pre_close *100
        
        rp.highest = float( data[3] )
        rp.lowest = float( data[4] )
        rp.bid_buy = float( data[5] )
        rp.bid_sell = float( data[6] )
        rp.volume = int( data[7] )
        rp.amount = int( float(data[8]) )
        
        if rp.amount == 0:return None
        
        for i in range(0, 10, 2):
            rp.slot_buy.append([ float(data[10+i]), int(data[9+i])])
            rp.slot_sell.append([ float(data[20+i]),int(data[19+i])])
            
        rp.date = data[-2]
        rp.time = data[-1]
    
    except:
        raise excep.NoPriceError(code, now)
    return rp
            
def get_rtprice(code, mcode=False):
    if not mcode:
        u = url%(get_market(code)+code)
    else:
        u = url%code
        
    h = httplib2.Http()
    resp, content = h.request(u, "GET") 
    s = content
    print s
    try:
        data = get_p_by_row(s)
    except excep.NoPriceError:
        return None     
    return data
